package com.mioto.ld.security.utils;

import cn.hutool.core.collection.CollUtil;
import com.mioto.ld.module.personal.model.User;
import com.mioto.ld.security.config.JwtConfig;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;
import java.util.Date;

/**
 * @author mioto-qinxj
 * @date 2024/4/11
 * @desc
 */
public class JwtTokenUtil {

    /**
     * 生成token
     * @param
     * @return
     */
    public static String createAccessToken(User user, Collection<? extends GrantedAuthority> authorities) {
        //登录成功生成token
        String token = Jwts.builder()
                .setId(String.valueOf(user.getId()))
                //主题
                .setSubject(user.getUsername())
                //签发时间
                .setIssuedAt(new Date())
                //签发者
                .setIssuer("mioto")
                .claim("logonUser",user)
                //自定义属性 放入用户角色
                .claim("authorities", CollUtil.join(authorities,","))
                //失效时间
                .setExpiration(new Date(System.currentTimeMillis() + JwtConfig.expiration))
                //签名算法和密钥
                .signWith(SignatureAlgorithm.HS512, JwtConfig.secret)
                .compact();
        return JwtConfig.tokenPrefix + token;
    }
}
